#!/usr/bin/env python
#-*- coding:utf-8 -*-
__author__ = "Naich An (An@Naich.org)"
__copyright__ = "Copyright (c) 2011 Naich An" 

#add the path to sys.path so *.py in the same dir could be found
import sys
sys.path.append('/home/naich/web/')
import os


import config #import the settings
import market


import web

import sys 
reload(sys) 
sys.setdefaultencoding('utf8') 


##########################settings################################
#debug setting
web.config.debug = True

urls = (
	'/','home',
	'/orderbook', 'orderbook',
	'/neworder','neworder',
	'/login','login',
	'/redirect','redirect',
	'/abort','abort',
	'/price','price',
	'/sidebar','sidebar',
	'/mylog','mylog',
	'/welcome','welcome',
	'/invite(.*)','invite',
	'/rank','rank',
	'/profile','profile'
	
)
app = web.application(urls, globals(), autoreload=False)
#templates folder setting
render = web.template.render('/home/naich/web/page/')

#redef notfound information	
def notfound():
	return web.notfound(render.notfound())
app.notfound = notfound


#########################pages######################################

class home:
	def GET(self):
		if web.cookies().get('name'): 
			raise web.seeother('/welcome')
		else:
		#if not logged, redirect to login page
			raise web.seeother('/login')
		
		
#login page		
class login:
	def GET(self):
		cookieName = web.cookies().get('name')
		if cookieName:
			web.setcookie('name','')
			return render.login(cookieName)
		else:
			return render.login("")

#save the login info and redirect to a new page.			
class redirect:
	def POST(self):
		cur = config.cur()
		i = web.input()
		if not i.name:
			raise web.seeother('/')
		cur.execute("SELECT user_id FROM user WHERE 1")
		#if name not in the userlist , access deny
		if (int(i.name),) not in cur.fetchall():
			return 'LOGIN FAILED! GO TO GET AN INVITATION FROM AN@NAICH.ORG'
		#if in the userlist, check its passwd		
		else:
			cur.execute("SELECT passwd FROM user WHERE user_id = '%s'"%i.name)
			if i.passwd != cur.fetchone()[0]:
				return "WRONG PASSWORD! CHECK IT AGAIN!"
			else:
				web.setcookie('name',i.name, 3600)
				raise web.seeother('/welcome')

#show the orderbook
class orderbook:
	def GET(self):
		if web.cookies().get('name'): 
			cur = config.cur()

			sellList,buyList = market.orderbook()
		
			return render.orderbook(web.cookies().get('name'),sellList,buyList,market.getinfo(int(web.cookies().get('name'))))
		else:
		#if not logged, redirect to login page
			raise web.seeother('/login')
		

#insert a new line into the orderbook
class neworder:
	def GET(self):
		if web.cookies().get('name'): 
			cur = config.cur()
			message = u'买单和卖单的价格最小变化在小数点后两位。'
		
			i = web.input()
			if i:
				message = market.neworder(int(web.cookies().get('name')),float(i.price), float(i.amount), int(i.order_type))
				#在订单进入后交易一次
				market.trade()
		
			return render.neworder(web.cookies().get('name'),message,market.getinfo(int(web.cookies().get('name'))))
		else:
		#if not logged, redirect to login page
			raise web.seeother('/login')
			
		
class abort:
	def GET(self):
		if web.cookies().get('name'): 
			cur = config.cur()
			i = web.input()
			
			message = ''
			try:		
				#abort the order
				message = market.abort(int(i.order_id),int(web.cookies().get('name')))
			except:
				pass
				
			return render.abort(web.cookies().get('name'),message,market.getinfo(int(web.cookies().get('name'))))
		else:
		#if not logged, redirect to login page
			raise web.seeother('/login')
			
class price:
	def GET(self):
		if web.cookies().get('name'): 
			cur = config.cur()
			i = web.input()
				
				
			try:
				start = market.datetime.datetime(2011,int(i.m),int(i.d))
				delta = market.datetime.timedelta(0,int(i.tick)*60)
				historyPriceByHourNum = market.historyPriceNum(startTime = start,timedelta = delta)
			except:
				#get the history data with preset data
				timeNow = market.datetime.datetime.now()
				historyPriceByHourNum = market.historyPriceNum(startTime = market.datetime.datetime(timeNow.year, timeNow.month, timeNow.day) - market.datetime.timedelta(5,0))
				
			
			return render.price(web.cookies().get('name'), market.getinfo(int(web.cookies().get('name'))), historyPriceByHourNum)
		else:
		#if not logged, redirect to login page
			raise web.seeother('/login')
			
class sidebar:
	def GET(self):
		if web.cookies().get('name'):
			return render.sidebar(web.cookies().get('name'),market.getinfo(int(web.cookies().get('name'))))

class mylog:
	def GET(self):
		if web.cookies().get('name'): 			
			return render.mylog(web.cookies().get('name'), market.tradelog(int(web.cookies().get('name'))), market.getinfo(int(web.cookies().get('name'))))
		else:
		#if not logged, redirect to login page
			raise web.seeother('/login')
		
class welcome:
	def GET(self):
		if web.cookies().get('name'): 			
			return render.welcome(web.cookies().get('name'), market.getinfo(int(web.cookies().get('name'))))
		else:
		#if not logged, redirect to login page
			raise web.seeother('/login')


class invite:
	#invite system, under construction
	def GET(self,invitecode):
		if invitecode:
			return invitecode[1:]
		else:
			r = market.historyPriceNum()
			return render.flot(r)
		
			
class rank:
	#give the rank information of a user
	def GET(self):
		if web.cookies().get('name'):
			cur = config.cur()
			
			#get the lastest price, if no price is generated before, set it to 10
			cur.execute('SELECT price FROM pricelist ORDER BY time DESC LIMIT 1')
			try:
				priceNow = cur.fetchone()[0]
			except:
				priceNow = 10
			
			standardWealth = 1000 + 100 * priceNow
			return render.rank(web.cookies().get('name'), market.getinfo(int(web.cookies().get('name'))), standardWealth)
		else:
		#if not logged, redirect to login page
			raise web.seeother('/login')
			
class profile:
	def GET(self):
		if web.cookies().get('name'):
			cur = config.cur()
			
			#get the nickname
			cur.execute('SELECT nick FROM user WHERE user_id = %d'%int(web.cookies().get('name')))
			nickname = cur.fetchone()[0]
			
			#get the input
			i = web.input()
			try:
				if i.nickname and not nickname:
					cur.execute('UPDATE user SET nick = "%s" WHERE user_id = %d'%(i.nickname,int(web.cookies().get('name'))))
					#update the nick name
					cur.execute('SELECT nick FROM user WHERE user_id = %d'%int(web.cookies().get('name')))
					nickname = cur.fetchone()[0]
			except:
				pass
			
			return render.profile(web.cookies().get('name'), market.getinfo(int(web.cookies().get('name'))), nickname, "")
		else:
		#if not logged, redirect to login page
			raise web.seeother('/login')
	
	def POST(self):	
		if web.cookies().get('name'):
			cur = config.cur()
			
			#get the nickname
			cur.execute('SELECT nick FROM user WHERE user_id = %d'%int(web.cookies().get('name')))
			nickname = cur.fetchone()[0]
			
			#get the input
			i = web.input()
			message = ""
			try:
				if i.newpass1 != i.newpass2:
					message = "两次输入的新密码不同"
				else:
					cur.execute("SELECT passwd FROM user WHERE user_id = '%s'"%web.cookies().get('name'))
					if i.oldpass != cur.fetchone()[0]:
						message = "密码错误，请重新输入"
					else:
						cur.execute("UPDATE user SET passwd = '%s' WHERE user_id = %d"%(i.newpass1, int(web.cookies().get('name'))))
						message = "密码更改成功，请重新登录"
						web.setcookie('name','')
						
			except:
				message = "密码更改失败，遇到未知错误"
			
			return render.profile(web.cookies().get('name'), market.getinfo(int(web.cookies().get('name'))), nickname, message)
		else:
		#if not logged, redirect to login page
			raise web.seeother('/login')	
			
application = app.wsgifunc()
































